<template>
    <view class="pub_page pub_ammeter_info">
        <image class="bg_img" mode="widthFix" :src="bg_manage" />
        <pub-head headerName="ammeter_info" :headerConfig="headerConfig"></pub-head>
        <div class="page_box page_box_scroll" v-show="deviceInfo != ''"
            :style="{ 'height': `calc(100vh - ${otherHeight})` }">
            <div class="region_div">
                <div class="left">
                    <image class="icon_1" mode="aspectFit"
                        src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_8.png" />
                    <div class="txt">{{ deviceInfo.area }} > {{ deviceInfo.room }}</div>
                </div>
            </div>
            <div class="info_div">
                <div class="lis">
                    <div class="li" v-if="deviceInfo != ''">
                        <div class="p_1">
                            <image class="icon_1" mode="aspectFit"
                                src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_15.png" />
                            {{ deviceInfo.name }}
                        </div>
                        <div class="p_2">
                            <div class="yuan" :class="deviceInfo.linkStatus=='online'?'':'yuan_red'"></div>
                            <!-- 1在线，0离线 -->
                            <div class="txt" :class="deviceInfo.linkStatus=='online'?'':'txt_red'">{{
                                deviceInfo.linkStatus=='online'?"在线":"离线" }}</div>
                            <!-- 1合闸  0断闸 -->
                            <div class="txt" :class="deviceInfo.switchStatus==1?'':'txt_red'">{{
                                deviceInfo.switchStatus==1?"合闸":"断闸" }}
                            </div>
                        </div>
                    </div>
                    <div class="li">
                        <div class="p_3">{{ deviceInfo ? deviceInfo.balance.toFixed(2) : 0 }}</div>
                        <div class="p_4">剩余金额(元)</div>
                    </div>
                    <div class="li li_1 li_no_margin">
                        <div class="p_5">{{ deviceInfo.consumption || 0 }}</div>
                        <div class="p_4">总用电量(度)</div>
                    </div>
                    <div class="li li_2 li_no_margin">
                        <div class="p_5">{{ deviceInfo.currentPlan || 0 }}</div>
                        <div class="p_4">收费标准(元/度)</div>
                    </div>
                </div>
                <div class="time">更新时间{{ deviceInfo.updateTime }}</div>
            </div>
            <div class="tools_div">
                <swiper class="swiper_box" @change="toolsSwiperChange">
                    <swiper-item>
                        <view class="swiper_item">
                            <div class="li" @click="modelDeal('open', 1)">
                                <image class="img" mode="aspectFit"
                                    src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_30.png" />
                                <div class="p">代充值</div>
                            </div>
                            <div class="li" @click="modelDeal('open', 2)">
                                <image class="img" mode="aspectFit"
                                    src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_31.png" />
                                <div class="p">退费</div>
                            </div>
                            <div class="li"
                                @click="$comFun.openWin('/pages/index/ammeter_check', { deviceId: deviceInfo.name })">
                                <image class="img" mode="aspectFit"
                                    src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_32.png" />
                                <div class="p">电表账单</div>
                            </div>
                            <div class="li" @click="switchStatus(1)">
                                <image class="img" mode="aspectFit"
                                    :src="deviceInfo.switchStatus != 1 ? 'https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_14.png' : 'https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_59.png'" />
                                <div class="p">合闸</div>
                            </div>
                        </view>
                    </swiper-item>
                    <swiper-item>
                        <view class="swiper_item">
                            <div class="li" @click="switchStatus(0)">
                                <image class="img" mode="aspectFit"
                                    :src="deviceInfo.switchStatus != 0 ? 'https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_13.png' : 'https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_60.png'" />
                                <div class="p">断闸</div>
                            </div>
                            <div class="li" @click="meterReading">
                                <image class="img" mode="aspectFit"
                                    src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_12.png" />
                                <div class="p">抄表</div>
                            </div>
                            <div class="li" @click="jump('/pages/index/add_device', { deviceId: deviceId, step: 2 })">
                                <image class="img" mode="aspectFit"
                                    src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_33.png" />
                                <div class="p">用户管理</div>
                            </div>
                            <div class="li" @click="jump('/pages/index/add_device', { deviceId: deviceId })">
                                <image class="img" mode="aspectFit"
                                    src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_34.png" />
                                <div class="p">电表编辑</div>
                            </div>
                        </view>
                    </swiper-item>
                </swiper>
                <div class="swiper_indicator">
                    <div class="li" :class="key == toolsSwiperKey ? 'li_active' : ''" v-for="(li, key) in 2" :key="key">
                    </div>
                </div>
            </div>
            <div class="data_div">
                <div class="li">
                    <div class="p_1">用能分析</div>
                </div>
                <div class="li">
                    <div class="p_2">{{ countInfo.total }}</div>
                    <div class="p_3">总用电量(度)</div>
                </div>
                <div class="li li_1">
                    <div class="p_4">{{ countInfo.day }}</div>
                    <div class="p_3">今日用电(度)</div>
                </div>
                <div class="li li_1">
                    <div class="p_4">{{ countInfo.week }}</div>
                    <div class="p_3">本周用电(度)</div>
                </div>
                <div class="li li_1">
                    <div class="p_4">{{ countInfo.month }}</div>
                    <div class="p_3">本月用电(度)</div>
                </div>
            </div>
            <div class="echart_div">
                <div class="title">电量(度)
                    <div class="month">
                        <picker mode="date" fields="month" :end="maxTime"
                            @change="(data) => pickerChange('year_month', data)">
                            {{ `${timeArr[0]}年${timeArr[1]}月` }}
                            <image class="icon" mode="aspectFit"
                                src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_16.png" />
                        </picker>
                    </div>
                </div>
                <l-echart class="echart_div_box" ref="echart_div" @finished="getEchartData"></l-echart>
            </div>
        </div>

        <div class="model_box" v-if="modelData.show">
            <div class="model_div">
                <div class="titles">{{ modelData.type == 1 ? '代充值' : '退费' }}
                    <image @click="modelDeal('close')" class="close" mode="aspectFit"
                        src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_57.png" />
                </div>
                <div class="pub_input">
                    <div class="li">
                        <div class="title"><text class="xing">*</text> 金额</div>
                        <div class="input">
                            <input class="inp" type="digit" v-model="amount" @input="dealPrice()" placeholder="请输入"
                                placeholder-style="color:#bbb">
                        </div>
                    </div>
                </div>
                <div class="pub_btn" @click="modelDeal('sure')">确定</div>
            </div>
        </div>
    </view>
</template>

<script>
import LEchart from '@/uni_modules/lime-echart/components/l-echart/l-echart.vue';
import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
export default {
    components: { LEchart },
    data() {
        return {
            headerConfig: {
                title: '电表',//标题栏内容
                title_color: '#fff',
                left_content: 'white',
            },
            otherHeight: getApp().globalData.otherHeight,
            toolsSwiperKey: 0,

            deviceId: '',
            deviceInfo: '',
            countInfo: { total: 0, month: 0, day: 0, week: 0 },

            timeArr: [0, 0],
            maxTime: '',

            amount: '',
            modelData: {
                show: false,
                type: 0,//1代充值  2退费
            },

            bg_manage: '',
        };
    },
    onLoad(options) {
        this.deviceId = options.id;
        console.log(options, this.deviceId);
        if (this.deviceId) {
            var today = new Date(); // 获取当前日期时间
            let month = today.getMonth() + 1;
            this.timeArr = [today.getFullYear(), `${month > 9 ? '' : '0'}${month}`];
            this.maxTime = `${today.getFullYear()}-${month > 9 ? '' : '0'}${month}`;

            this.getDeviceInfo();
            this.getCount();
        }

        const that = this;
        uni.$off('deviceUpdateBack_info');
        uni.$on('deviceUpdateBack_info', function (data) {
            // console.log(data);
            that.getDeviceInfo();
        })
    },
    onShow() {
        if (this.$store.state.standing == 'manage') {
            const bg_manage = uni.getStorageSync('bg_manage');
            this.bg_manage = bg_manage || this.$store.state.bg_normal_manage;
        }
    },
    methods: {
        dealPrice() {
            // console.log(this.form.fixedCharge.unitPrice);usageThreshold
            let value = this.amount;
            // value = value.replace(/[^\d.]/g, "");//清除"数字"和"."以外的字符    
            value = value.replace(/^\./g, "");//验证第一个字符是数字而不是字符    
            value = value.replace(/\.{2,}/g, ".");//只保留第一个.清除多余的    
            value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
            value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数  
            setTimeout(() => {
                this.amount = value;
                this.$forceUpdate();
            }, 1);
        },
        async getDeviceInfo() {
            this.$comFun.openLoading();
            const res = await this.$request.get(`/mobile/manager/device/detail/${this.deviceId}`, {});
            this.$comFun.closeLoading();
            // console.log(res);
            if (res.code == 200) {
                this.deviceInfo = res.data;
            }
        },
        async getCount() {
            const res = await this.$request.get(`/mobile/manager/device/stat_consumption/${this.deviceId}`, {});
            // console.log(res);
            if (res.code == 200) {
                this.countInfo = res.data;
            }
        },
        meterReading() {
            if (this.deviceInfo.linkStatus == 'offline') {
                this.$comFun.toast('设备离线状态不支持该操作');
                return;
            }
            const that = this;
            uni.showModal({
                title: '提示',
                content: `是否确定抄表？`,
                success: async function (modalRes) {
                    if (modalRes.confirm) {
                        that.$comFun.openLoading(`正在抄表中`);
                        let res = await that.$request.put(`mobile/customer/device/meterReading/${that.deviceInfo.id}`, {});
                        if (res.code == 200) {
                            setTimeout(() => {
                                that.$comFun.toast(`抄表成功`);
                                setTimeout(() => {
                                    that.getDeviceInfo();
                                }, 1000)
                            }, 3000)
                        } else {
                            that.$comFun.closeLoading();
                            that.$comFun.toast(res.msg);
                        }
                    }
                }
            });
        },
        pickerChange(type, e) {
            // console.log(type, e.detail.value);
            if (type == 'year_month') {
                this.timeArr = e.detail.value.split("-");
            }
            this.getEchartData();
        },
        async getEchartData() {
            const res = await this.$request.get(`/mobile/manager/device/stat_month_consumption/${this.deviceId}`, {
                date: `${this.timeArr[0]}-${this.timeArr[1]}`
            });
            // console.log(res);
            if (res.code == 200) {
                let dataA = Object.keys(res.data);
                let dataB = Object.values(res.data);
                // console.log(dataA, dataB);

                setTimeout(() => {
                    this.initEcharts(dataA, dataB);
                }, 400);
            }
        },
        async modelDeal(type, type_1) {
            if (type == 'open') {
                this.amount = '';
                this.modelData = {
                    show: true,
                    type: type_1,//1代充值  2退费
                }
            }
            if (type == 'close') {
                this.modelData = {
                    show: false,
                    type: 0,//1代充值  2退费
                }
            }
            if (type == 'sure') {
                if (!this.amount) {
                    this.$comFun.toast('请先填写金额');
                    return;
                }
                if (this.modelData.type == 2 && Number(this.amount) > Number(this.deviceInfo.balance)) {
                    this.$comFun.toast('退费金额大于剩余金额');
                    return;
                }
                const that = this;
                uni.showModal({
                    title: '提示',
                    content: '是否确定操作？',
                    success: async function (modalRes) {
                        if (modalRes.confirm) {
                            that.$comFun.openLoading();
                            let urls = ['mobile/manager/order/adminRecharge', 'mobile/manager/order/adminRefund'];
                            const res = await that.$request.post(urls[that.modelData.type - 1], {
                                deviceId: that.deviceId,
                                amount: Number(that.amount),
                            });
                            that.$comFun.closeLoading();
                            // console.log(res);
                            if (res.code == 200) {
                                that.$comFun.toast('操作成功');
                                if (that.modelData.type == 1) {
                                    that.deviceInfo.balance = Number(that.deviceInfo.balance) + Number(that.amount)
                                } else if (that.modelData.type == 2) {
                                    that.deviceInfo.balance = Number(that.deviceInfo.balance) - Number(that.amount)
                                }
                                that.modelDeal('close');
                            } else {
                                that.$comFun.toast(res.msg);
                            }
                        }
                    }
                });
            }
        },
        switchStatus(status) {
            if (this.deviceInfo.switchStatus == status) {
                return;
            }
            if (this.deviceInfo.linkStatus == 'offline') {
                this.$comFun.toast('设备离线状态不支持该操作');
                return;
            }
            const that = this;
            // "0":断闸，"1":合闸
            uni.showModal({
                title: '提示',
                content: `是否确定${status == 0 ? '断闸' : '合闸'}？`,
                success: async function (modalRes) {
                    if (modalRes.confirm) {
                        that.$comFun.openLoading();
                        let res = await that.$request.put(`mobile/manager/device/switch/${that.deviceId}`, {
                            status: String(status)
                        });
                        that.$comFun.closeLoading();
                        if (res.code == 200) {
                            that.$comFun.toast(`${status == 0 ? '断闸' : '合闸'}成功`);
                            uni.$emit(`deviceUpdateBack_index`);
                            that.deviceInfo.switchStatus = status;
                        } else {
                            that.$comFun.toast(res.msg);
                        }
                    }
                }
            });
        },

        toolsSwiperChange(e) {
            this.toolsSwiperKey = e.target.current;
        },
        async initEcharts(dataA, dataB) {
            const chart = await this.$refs.echart_div.init(echarts);
            const option = {
                grid: {
                    left: '2%',
                    right: '2%',
                    bottom: '1%',
                    top: '10%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    triggerEvent: true,
                    axisLabel: {
                        interval: 'auto',
                        textStyle: {
                            color: '#333'
                        }
                    },
                    data: dataA,
                    axisLine: {
                        lineStyle: {
                            type: 'solid',
                            color: '#BFBFBF'
                        }
                    },
                    axisTick: {
                        show: true
                    }
                },
                yAxis: {
                    type: 'value',
                    axisLine: {
                        lineStyle: {
                            color: '#333'
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            type: 'dashed',
                            color: 'rgba(0, 0, 0, 0.15)'
                        }
                    },
                },
                series: [
                    {
                        data: dataB,
                        type: 'line',
                        showSymbol: true,
                        smooth: true,
                        lineStyle: {
                            color: '#3296FA',
                            width: 5
                        },
                        symbolSize: function (data) { // 自定义symbol大小函数
                            return 8; // 随机生成符合正态分布的大小值
                        },
                        itemStyle: {
                            color: '#3296FA' // 设置空心圆的边界色为白色
                        }
                    }
                ]
            };
            chart.setOption(option)
        },
        jump(href, params) {
            if (this.deviceInfo.linkStatus == 'offline') {
                this.$comFun.toast('设备离线状态不支持该操作');
                return;
            }
            this.$comFun.openWin(href, params);
        }
    },
};
</script>

<style lang="scss" scoped>
@import "@/common/css/index.scss";
</style>
